#include "Renderer.h"
#include "AnimationManager.h"
#include "TileManager.h"
#include "ObjectManager.h"
#include "../wrappers/CSGD_Direct3D.h"
#include "BaseObject.h"
#include "Camera.h"

#include <cassert>

CRenderer* CRenderer::s_Instance = nullptr;



CRenderer* CRenderer::GetInstance( void )
{
	if( s_Instance == nullptr )
		s_Instance = new CRenderer;

	return s_Instance;
}


void CRenderer::DeleteInstance( void )
{
	if( s_Instance != nullptr )
	{
		delete s_Instance;
		s_Instance = nullptr;
	}
}


CRenderer::CRenderer(void)
{
	m_pAnimManager	= nullptr;
	m_pTileManager	= nullptr;
}


CRenderer::~CRenderer(void)
{
}


void CRenderer::Initialize( void )
{
	
}


void CRenderer::Shutdown( void )
{
	m_pAnimManager		= nullptr;
	m_pTileManager		= nullptr;
}


void CRenderer::RenderScene( void )
{
	RenderLevel();
	RenderObjects();
}


void CRenderer::RenderObjects( void )
{
	CCamera* pCamera = CCamera::GetInstance();
	vector< CBaseObject* >::iterator objIter = pCamera->m_VisibleObjects.begin();
	for( ; objIter != pCamera->m_VisibleObjects.end(); ++objIter )
	{
		CSGD_Direct3D::GetInstance()->DrawRect((*objIter)->GetRect(),0,255,0);
		CSGD_Direct3D::GetInstance()->DrawRect((*objIter)->GetBaseRect(),255,255,255);
		// m_pAnimManager::GetInstance()->RenderAnimation( &(*objectIter)->GetAnimInfo() );
	}
}


void CRenderer::RenderLevel( void )
{
	if( m_pTileManager != nullptr )
		m_pTileManager->RenderMap();
}


void CRenderer::UpdateLevel( void )
{
	if( m_pTileManager != nullptr )
		m_pTileManager->UpdateMap( CCamera::GetInstance()->UpdateCamera() );
}


void CRenderer::HandleCollision( void )
{
	CObjectManager* pOM = CObjectManager::GetInstance();
	for( CObjectManager::ObjectIter iterI = pOM->m_Objects.begin(); iterI != pOM->m_Objects.end(); ++iterI )
	{
		if( m_pTileManager != nullptr )
		{
			assert( dynamic_cast< CBaseObject* >( (*iterI) ) && "CRenderer::HandleCollision - unable to convert to CBaseObject*" );
			m_pTileManager->CheckWorldCollision( dynamic_cast< CBaseObject* >( (*iterI) ) );
		}

		for( CObjectManager::ObjectIter iterK = pOM->m_Objects.begin(); iterK != pOM->m_Objects.end(); ++iterK )
		{
			if( (*iterI)->CheckCollision((*iterK)) == true )
			{
				// if  iterI == hammer
				//	{
						// send iterK->knockback(iterI)
				//  }
				// else
				break;
			}
				
		}
	}
}
